<template>
  <div class="news-manage">
    <div class="page-header">
      <h2>资讯管理</h2>
      <el-button type="primary" @click="handleCreate">
        <el-icon><Plus /></el-icon>
        新增资讯
      </el-button>
    </div>
    
    <el-card>
      <template #header>
        <div class="table-header">
          <span>资讯列表</span>
          <div class="header-actions">
            <el-select
              v-model="filterCategory"
              placeholder="分类筛选"
              style="width: 120px; margin-right: 10px;"
              clearable
            >
              <el-option label="全部分类" value="" />
              <el-option 
                v-for="category in categories" 
                :key="category.id"
                :label="category.name" 
                :value="category.name" 
              />
            </el-select>
            <el-select
              v-model="filterStatus"
              placeholder="发布状态"
              style="width: 120px; margin-right: 10px;"
              clearable
            >
              <el-option label="全部状态" value="" />
              <el-option label="已发布" value="published" />
              <el-option label="未发布" value="draft" />
            </el-select>
            <el-select
              v-model="filterTop"
              placeholder="置顶状态"
              style="width: 120px; margin-right: 10px;"
              clearable
            >
              <el-option label="全部" value="" />
              <el-option label="置顶" value="top" />
              <el-option label="普通" value="normal" />
            </el-select>
            <el-input
              v-model="searchKeyword"
              placeholder="搜索资讯标题"
              style="width: 200px; margin-right: 10px;"
              clearable
            />
            <el-button @click="handleSearch">搜索</el-button>
            <el-button @click="handleReset">重置</el-button>
          </div>
        </div>
      </template>
      
      <el-table :data="newsList" v-loading="loading">
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column prop="title" label="资讯标题" min-width="200" />
        <el-table-column prop="category" label="分类" width="120" />
        <el-table-column prop="viewCount" label="浏览量" width="100" />
        <el-table-column prop="likeCount" label="点赞数" width="100" />
        <el-table-column prop="isPublished" label="发布状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.isPublished ? 'success' : 'info'">
              {{ scope.row.isPublished ? '已发布' : '草稿' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="isTop" label="置顶" width="80">
          <template #default="scope">
            <el-tag v-if="scope.row.isTop" type="warning">置顶</el-tag>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="publishTime" label="发布时间" width="180" />
        <el-table-column label="操作" width="240" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button 
              size="small" 
              :type="scope.row.isPublished ? 'info' : 'success'"
              @click="handleToggleStatus(scope.row)"
            >
              {{ scope.row.isPublished ? '取消发布' : '发布' }}
            </el-button>
            <el-button 
              size="small" 
              type="danger"
              @click="handleDelete(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 资讯编辑对话框 -->
    <el-dialog
      v-model="newsDialogVisible"
      :title="newsDialogTitle"
      width="800px"
    >
      <el-form :model="newsForm" label-width="80px" :rules="newsRules" ref="newsFormRef">
        <el-form-item label="资讯标题" prop="title">
          <el-input 
            v-model="newsForm.title" 
            placeholder="请输入资讯标题" 
            maxlength="100" 
            show-word-limit 
          />
        </el-form-item>
        <el-form-item label="分类" prop="category">
          <el-select v-model="newsForm.category" placeholder="请选择分类" style="width: 100%;">
            <el-option 
              v-for="category in categories" 
              :key="category.id"
              :label="category.name" 
              :value="category.name" 
            />
          </el-select>
        </el-form-item>
        <el-form-item label="封面图片" prop="coverImage">
          <el-input 
            v-model="newsForm.coverImage" 
            placeholder="请输入封面图片URL" 
          />
        </el-form-item>
        <el-form-item label="资讯内容" prop="content">
          <el-input 
            v-model="newsForm.content" 
            type="textarea" 
            :rows="8" 
            placeholder="请输入资讯内容" 
            maxlength="5000" 
            show-word-limit 
          />
        </el-form-item>
        <el-form-item label="置顶" prop="isTop">
          <el-switch v-model="newsForm.isTop" active-text="置顶" inactive-text="普通" />
        </el-form-item>
        <el-form-item label="发布状态" prop="isPublished">
          <el-switch v-model="newsForm.isPublished" active-text="发布" inactive-text="草稿" />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="newsDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleNewsSubmit" :loading="submitLoading">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { newsService } from '../../services/newsService'

const loading = ref(false)
const submitLoading = ref(false)
const searchKeyword = ref('')
const filterCategory = ref('')
const filterStatus = ref('')
const filterTop = ref('')
const newsList = ref([])
const newsDialogVisible = ref(false)
const newsDialogTitle = ref('新增资讯')
const newsFormRef = ref()
const categories = ref([])


const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

const newsForm = reactive({
  id: null,
  title: '',
  content: '',
  coverImage: '',
  category: '',
  isPublished: false,
  isTop: false
})

const newsRules = {
  title: [
    { required: true, message: '请输入资讯标题', trigger: 'blur' },
    { min: 5, max: 100, message: '资讯标题长度在 5 到 100 个字符', trigger: 'blur' }
  ],
  category: [
    { required: true, message: '请选择分类', trigger: 'change' }
  ],
  content: [
    { required: true, message: '请输入资讯内容', trigger: 'blur' },
    { min: 10, max: 5000, message: '资讯内容长度在 10 到 5000 个字符', trigger: 'blur' }
  ]
}






// 加载分类列表
const loadCategories = async () => {
  try {
    const response = await newsService.getNewsCategories()
    categories.value = response.data || []
  } catch (error) {
    console.error('加载分类列表失败:', error)
    ElMessage.error('加载分类列表失败')
  }
}

// 加载资讯列表
const loadNewsList = async () => {
  try {
    loading.value = true
    
    const params = {
      page: pagination.current,
      size: pagination.size
    }
    
    // 添加所有筛选条件到请求参数
    if (searchKeyword.value) {
      params.keyword = searchKeyword.value
    }
    if (filterCategory.value) {
      params.category = filterCategory.value
    }
    if (filterStatus.value) {
      params.isPublished = filterStatus.value === 'published'
    }
    if (filterTop.value) {
      params.isTop = filterTop.value === 'top'
    }
    
    const response = await newsService.getNewsList(params)
    newsList.value = response.data?.content || []
    pagination.total = response.data?.totalElements || 0
  } catch (error) {
    console.error('加载资讯列表失败:', error)
    ElMessage.error('加载资讯列表失败')
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  pagination.current = 1
  loadNewsList()
}

const handleReset = () => {
  searchKeyword.value = ''
  filterCategory.value = ''
  filterStatus.value = ''
  filterTop.value = ''
  pagination.current = 1
  loadNewsList()
}

const handleCreate = () => {
  newsDialogTitle.value = '新增资讯'
  Object.assign(newsForm, {
    id: null,
    title: '',
    content: '',
    coverImage: '',
    category: '',
    isPublished: false,
    isTop: false
  })
  newsDialogVisible.value = true
  
  // 清除表单验证
  nextTick(() => {
    if (newsFormRef.value) {
      newsFormRef.value.clearValidate()
    }
  })
}

const handleEdit = (row) => {
  newsDialogTitle.value = '编辑资讯'
  Object.assign(newsForm, { ...row })
  newsDialogVisible.value = true
  
  // 清除表单验证
  nextTick(() => {
    if (newsFormRef.value) {
      newsFormRef.value.clearValidate()
    }
  })
}

const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除资讯 "${row.title}" 吗？删除后无法恢复！`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await newsService.deleteNews(row.id)
    ElMessage.success('删除成功')
    loadNewsList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除资讯失败:', error)
      ElMessage.error('删除资讯失败')
    }
  }
}

const handleToggleStatus = async (row) => {
  try {
    const action = row.isPublished ? '取消发布' : '发布'
    await ElMessageBox.confirm(
      `确定要${action}资讯 "${row.title}" 吗？`,
      `${action}确认`,
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 调用API更新资讯状态
    await newsService.updateNewsStatus(row.id, !row.isPublished)
    ElMessage.success(`${action}成功`)
    loadNewsList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('更新资讯状态失败:', error)
      ElMessage.error(`${action}失败`)
    }
  }
}

const handleNewsSubmit = async () => {
  try {
    // 表单验证
    await newsFormRef.value.validate()
    
    submitLoading.value = true
    
    if (newsForm.id) {
      // 编辑资讯
      await newsService.updateNews(newsForm.id, newsForm)
      ElMessage.success('编辑资讯成功')
    } else {
      // 新增资讯
      await newsService.createNews(newsForm)
      ElMessage.success('新增资讯成功')
    }
    
    newsDialogVisible.value = false
    loadNewsList()
  } catch (error) {
    if (error && error.errors) {
      // 表单验证错误，不显示错误消息
      return
    }
    console.error('保存资讯失败:', error)
    ElMessage.error('保存资讯失败')
  } finally {
    submitLoading.value = false
  }
}

const handleSizeChange = (size) => {
  pagination.size = size
  pagination.current = 1
  loadNewsList()
}

const handleCurrentChange = (current) => {
  pagination.current = current
  loadNewsList()
}

onMounted(async () => {
  await loadCategories()
  await loadNewsList()
})
</script>

<style scoped>
.news-manage {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #333;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  align-items: center;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}
</style>